#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "st7789.h"
#include "gbk.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_err.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_vfs.h"
#include "esp_spiffs.h"
int SwitchToGbk(const unsigned char* pszBufIn, int nBufInLen, unsigned char* pszBufOut, int* pnBufOutLen)
{
	int i = 0;
	int j = 0;
	unsigned short unicode;
	char gbk[50];
    char file[30];
    strcpy(file, "/spiffs/c2b.bin");
	FILE* fp = fopen(file, "rb");
	if (fp == NULL) {
	    ESP_LOGW(__FUNCTION__, "File not found [%s]", file);
	    return -1;
	 }
	for(; i < nBufInLen; i++, j++)
	{
		if((pszBufIn[i] & 0x80) == 0x00)		// 1?
		{
			pszBufOut[j]= pszBufIn[i];
		}
		else if ((pszBufIn[i] & 0xF0) == 0xE0) // 3? 
		{
            
			if (i+ 2 >= nBufInLen) return -1; 
			unicode = (((int)(pszBufIn[i] & 0x0F)) << 12) | (((int)(pszBufIn[i+1] & 0x3F)) << 6) | (pszBufIn[i+2]  & 0x3F); 
			

	        fseek(fp, 2*(unicode-0x4e00), SEEK_SET );
	        fread(gbk, 1,2, fp);	 
	           
            
            // SPI_Flash_Read(gbk,utf8_info.utf8togbkddr+(2*(unicode-0x4e00)),2);
			 pszBufOut[j]= gbk[1];//gbk%256;
			 pszBufOut[j+1] = gbk[0];//gbk/256;.
			j++;
			i+=2;
		}
		else
		{
            
            ESP_LOGI("U2C", "不知原因");
			return -1;
		}
	}
	*pnBufOutLen = j;
    pszBufOut[j]=0;
     fclose(fp);
	return 0;
}
int lcd_show_utf8(u16 x,u16 y,char*str,u8 len,uint16_t color)
{
    char gbkstr[100];
    int gbklen;
    if(SwitchToGbk((const unsigned char *)str, strlen(str), (unsigned char *)gbkstr,&gbklen)){
	ESP_LOGI("U2Gz", "转换失败");		
	}

	Show_Str_Mid(x,y,gbkstr,16,len, WHITE);
    return gbklen;
}
int lcd_draw_utf8_ram(u16 x,u16 y,char*str,u8 len,uint16_t color,uint16_t *data,int w,int h)
{
    char gbkstr[100];
    int gbklen;
    if(SwitchToGbk((const unsigned char *)str, strlen(str), (unsigned char *)gbkstr,&gbklen)){
	ESP_LOGI("U2Gz", "转换失败");		
	}

	Show_Mid_Ram(x,y,gbkstr,16,len, WHITE,data,w,h);
    return gbklen;
}